/**
 * 封装自动轮播插件
 * author aty
 */

$.fn.autoSilder = function(options){
	let self = this;
	let config = {
		autoPlay:true,
		vis:1,
		time:5
	}

	$.extend(config,options);

	this.timer = null;
	this.curPos = 1;
	this.silderUl = $(this).find(options.mainCell);

	this.childLen = this.silderUl.children().length;
	this.parentWidth = this.silderUl.parent().width();

	this.navUl = $(options.navCell);


	this.navUl.children().each((i,item)=>{
		item.onclick = function(e){
			config.pageChange && config.pageChange(i);
			self.toPage(i);
		}
	})
	
	this.initStyle = ()=> {
		this.silderUl.children().width( this.parentWidth );
		this.silderUl.width( this.parentWidth*this.childLen );
	}

	this.changeNavIdx = function(curPos){
		this.navUl.children().removeClass("on");
		this.navUl.children().eq(curPos).addClass("on");
	}

	this.changeLiIdx = function(curPos){
		this.silderUl.children().removeClass("on");
		this.silderUl.children().eq(curPos).addClass("on");
	}

	this.initStyle();

	$(this).mouseenter(()=>{
		if(config.autoPlay){
			clearInterval(this.timer)
		}
	})

	$(this).mouseleave(()=>{
		if(config.autoPlay){
			this.initTimer();
		}
	})

	this.initTimer = ()=>{
		this.timer = setInterval(()=>{
			if(this.curPos==this.childLen){
				this.curPos = 0;
			}
			this.changeNavIdx(this.curPos);
			this.changeLiIdx(this.curPos);
			this.silderUl.css("transform",`translateX(-${this.parentWidth*this.curPos}px)`);
			this.curPos = this.curPos + 1;
		},config.time*1000);
	}


	this.autoPlay = ()=>{
		this.initTimer();
	}

	if(config.autoPlay){
		this.autoPlay();
	}

	this.toPage = function(idx){
		self.curPos = idx;
		self.silderUl.css("transform",`translateX(-${self.parentWidth*self.curPos}px)`);
		self.changeNavIdx(idx);
		self.changeLiIdx(idx);
	}
}

// 调用说明
/*$("#energy").autoSilder({
	navCell:"div.silder-title",
	mainCell:"ul.type-ul",
	autoPlay:false,
	pageChange:function(i){
 		console.log(i)
 	}
})*/